package root.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.Consumer;

public class CommandHandler {
    private static CommandHandler commandHandler;
    private Runtime runtime;

    private CommandHandler(){
        runtime=Runtime.getRuntime();
    }

    public static CommandHandler getInstance() {
        if(commandHandler==null){
            synchronized (CommandHandler.class){
                commandHandler=new CommandHandler();
            }
        }
        return commandHandler;
    }
    public Process execCommand(String[] cmdarray){
        return execCommand(cmdarray,null,null);
    }
    public Process execCommand(String[] cmdarray, String[] envp){
        return execCommand(cmdarray,envp,null);
    }
    public Process execCommand(String[] cmdarray, String[] envp, Consumer<String> callback){
        Process process=null;
        try {
            process = runtime.exec(cmdarray, envp);
            if (callback!=null){
                var reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GB18030"));
                String line;
                var fullPrint = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    fullPrint.append(line).append('\n');
                }
                reader.close();
                callback.accept(fullPrint.toString().strip());
            }
        } catch (IOException e) {
            System.err.println("执行命令失败："+e.getMessage());
            e.printStackTrace();
        }
        return process;
    }
}
